package auctionhaus

import grails.gorm.DetachedCriteria
import org.springframework.dao.DataIntegrityViolationException

class ListingController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index() {
        redirect(action: "list", params: params)
    }
	
	def createBid() {
		
		params.remove("listing")  //this param is un-needed and causes errors.
		
		redirect(controller: "bid", action: "create",  params: params)
	}

    def list() {
		
		println params
		
		//M-2: The main landing page shows up to 5 listings at a time
		//M-3: If more than 5 listings exist, pagination links will be available to let the user page through the listings
        params.max = Math.min(params.max ? params.int('max') : 5, 100) 
		
		//M-4: Only listings with a end date/time that is in the future are visible on the main page
		//M-1: The main landing page shows listings sorted by the date they were created (most recent first)
		def criteria = new DetachedCriteria(Listing).build {
			gt 'endDateTime',(new Date())
		}
		
		//ordering is moved to here, so we can still sort other columns if user desires
		//defaults to dateCreated sorting.
		if(!params.containsKey('sort')){
			params['sort'] = 'dateCreated'
			params['order'] = 'desc'
		}
		
		List listings = criteria.list(params);
		

		//requires 2 criterias because one above doesn't like order clause
		//can't use listings.size() because params.max is set to 5.
		def listingsCount = new DetachedCriteria(Listing).build {
			gt 'endDateTime',(new Date())
		}
		
		[listingInstanceList: listings, listingInstanceTotal: listingsCount.count()]
		
    }

    def create() {
        [listingInstance: new Listing(params)]
    }

    def save() {
        def listingInstance = new Listing(params)
        if (!listingInstance.save(flush: true)) {
            render(view: "create", model: [listingInstance: listingInstance])
            return
        }

		flash.message = message(code: 'default.created.message', args: [message(code: 'listing.label', default: 'Listing'), listingInstance.id])
        redirect(action: "show", id: listingInstance.id)
    }

    def show() {
        def listingInstance = Listing.get(params.id)
        if (!listingInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'listing.label', default: 'Listing'), params.id])
            redirect(action: "list")
            return
        }

        [listingInstance: listingInstance]
    }

    def edit() {
        def listingInstance = Listing.get(params.id)
        if (!listingInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'listing.label', default: 'Listing'), params.id])
            redirect(action: "list")
            return
        }

        [listingInstance: listingInstance]
    }

    def update() {
        def listingInstance = Listing.get(params.id)
        if (!listingInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'listing.label', default: 'Listing'), params.id])
            redirect(action: "list")
            return
        }

        if (params.version) {
            def version = params.version.toLong()
            if (listingInstance.version > version) {
                listingInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'listing.label', default: 'Listing')] as Object[],
                          "Another user has updated this Listing while you were editing")
                render(view: "edit", model: [listingInstance: listingInstance])
                return
            }
        }

        listingInstance.properties = params

        if (!listingInstance.save(flush: true)) {
            render(view: "edit", model: [listingInstance: listingInstance])
            return
        }

		flash.message = message(code: 'default.updated.message', args: [message(code: 'listing.label', default: 'Listing'), listingInstance.id])
        redirect(action: "show", id: listingInstance.id)
    }

    def delete() {
        def listingInstance = Listing.get(params.id)
        if (!listingInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'listing.label', default: 'Listing'), params.id])
            redirect(action: "list")
            return
        }

        try {
            listingInstance.delete(flush: true)
			flash.message = message(code: 'default.deleted.message', args: [message(code: 'listing.label', default: 'Listing'), params.id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
			flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'listing.label', default: 'Listing'), params.id])
            redirect(action: "show", id: params.id)
        }
    }
}
